<template>
  <div class="reset-password-page">
    <h2 class="page-title">{{ $t('auth.resetPassword.title') }}</h2>
    <p class="page-subtitle">{{ $t('auth.resetPassword.subtitle') }}</p>
    
    <el-form
      ref="formRef"
      :model="resetForm"
      :rules="rules"
      label-position="top"
      size="large"
    >
      <el-form-item :label="$t('auth.resetPassword.verificationCode')" prop="verificationCode">
        <el-input
          v-model="resetForm.verificationCode"
          :placeholder="$t('auth.resetPassword.verificationCode')"
          prefix-icon="Key"
          maxlength="6"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item :label="$t('auth.resetPassword.newPassword')" prop="newPassword">
        <el-input
          v-model="resetForm.newPassword"
          type="password"
          :placeholder="$t('auth.resetPassword.newPassword')"
          prefix-icon="Lock"
          show-password
        />
      </el-form-item>
      
      <el-form-item :label="$t('auth.resetPassword.confirmPassword')" prop="confirmPassword">
        <el-input
          v-model="resetForm.confirmPassword"
          type="password"
          :placeholder="$t('auth.resetPassword.confirmPassword')"
          prefix-icon="Lock"
          show-password
        />
      </el-form-item>
      
      <el-form-item>
        <el-button
          type="primary"
          size="large"
          style="width: 100%"
          :loading="loading"
          :disabled="isSubmitting"
          @click="handleSubmit"
        >
          {{ isSubmitting ? '重置中...' : $t('auth.resetPassword.resetPassword') }}
        </el-button>
      </el-form-item>
    </el-form>
    
    <div class="auth-actions">
      <router-link to="/auth/forgot-password" class="back-link">
        <el-icon><ArrowLeft /></el-icon>
        重新获取验证码
      </router-link>
      
      <span class="divider">|</span>
      
      <router-link to="/auth/login" class="back-link">
        {{ $t('auth.resetPassword.backToLogin') }}
      </router-link>
    </div>
    
    <!-- 邮箱信息提示 -->
    <div v-if="email" class="email-info">
      <el-alert
        :title="`验证码已发送到: ${email}`"
        type="info"
        :closable="false"
        show-icon
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import type { ResetPasswordForm } from '@/types'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 表单引用
const formRef = ref<FormInstance>()
const loading = ref(false)
const email = ref('')

// 表单数据
const resetForm = reactive<ResetPasswordForm>({
  email: '',
  verificationCode: '',
  newPassword: '',
  confirmPassword: ''
})

// 自定义验证函数
const validateConfirmPassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== resetForm.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 表单验证规则
const rules: FormRules = {
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度为6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

// 防抖处理
const isSubmitting = ref(false)

/**
 * 处理重置密码
 */
const handleSubmit = async () => {
  if (!formRef.value || isSubmitting.value) return

  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    isSubmitting.value = true
    loading.value = true

    const result = await userStore.resetPassword(resetForm)

    if (result.success) {
      ElMessage({
        message: result.message,
        type: 'success',
        duration: 3000,
        showClose: true
      })

      // 成功后跳转到登录页面
      setTimeout(() => {
        router.push('/auth/login')
      }, 1500)
    } else {
      ElMessage({
        message: result.message,
        type: 'error',
        duration: 3000,
        showClose: true
      })
    }
  } catch (error) {
    console.error('重置密码失败:', error)
    ElMessage({
      message: '重置密码失败，请重试',
      type: 'error',
      duration: 3000,
      showClose: true
    })
  } finally {
    loading.value = false
    setTimeout(() => {
      isSubmitting.value = false
    }, 1000)
  }
}

// 初始化页面
onMounted(() => {
  const emailParam = route.query.email as string
  if (emailParam) {
    email.value = emailParam
    resetForm.email = emailParam
  } else {
    // 如果没有邮箱参数，跳转到忘记密码页面
    ElMessage({
      message: '请先获取验证码',
      type: 'warning'
    })
    router.push('/auth/forgot-password')
  }
})
</script>

<style lang="scss" scoped>
.reset-password-page {
  .page-title {
    text-align: center;
    font-size: var(--font-size-2xl);
    font-weight: 600;
    color: var(--text-primary);
    margin-bottom: var(--spacing-md);
  }
  
  .page-subtitle {
    text-align: center;
    color: var(--text-secondary);
    margin-bottom: var(--spacing-2xl);
    line-height: 1.6;
  }
  
  .auth-actions {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: var(--spacing-md);
    margin-top: var(--spacing-lg);
    
    .back-link {
      color: var(--primary-color);
      text-decoration: none;
      display: inline-flex;
      align-items: center;
      gap: var(--spacing-xs);
      
      &:hover {
        color: var(--primary-dark);
      }
    }
    
    .divider {
      color: var(--text-secondary);
    }
  }
  
  .email-info {
    margin-top: var(--spacing-xl);
    
    :deep(.el-alert__content) {
      text-align: center;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .reset-password-page {
    .auth-actions {
      flex-direction: column;
      gap: var(--spacing-sm);
      
      .divider {
        display: none;
      }
    }
  }
}
</style> 